package com.swak.consistency.core.handle.impls;

import java.util.List;

import com.swak.consistency.core.context.ConsistencyContext;
import com.swak.consistency.core.execption.ConsistencyException;
import com.swak.consistency.core.handle.ConsistencyHandler;
import com.swak.utils.Lists;

/**
 * 根据类型处理
 * 
 * @author lifeng
 * @date 2021年1月27日 上午9:38:35
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class MultiConsistencyHandler implements ConsistencyHandler {

	List<ConsistencyHandler> handlers = Lists.newArrayList();

	public MultiConsistencyHandler addHandler(ConsistencyHandler handler) {
		this.handlers.add(handler);
		return this;
	}

	public MultiConsistencyHandler addHandlers(List<ConsistencyHandler> handlers) {
		this.handlers.addAll(handlers);
		return this;
	}

	@Override
	public Object prepare(ConsistencyContext context) {
		for (ConsistencyHandler handler : handlers) {
			if (handler.support(context)) {
				return handler.prepare(context);
			}
		}
		throw new ConsistencyException("No Handler For " + context.toString());
	}

	@Override
	public Object transmit(ConsistencyContext context) {
		for (ConsistencyHandler handler : handlers) {
			if (handler.support(context)) {
				return handler.transmit(context);
			}
		}
		throw new ConsistencyException("No Handler For " + context.toString());
	}

	@Override
	public Object complete(ConsistencyContext context) {
		for (ConsistencyHandler handler : handlers) {
			if (handler.support(context)) {
				return handler.complete(context);
			}
		}
		throw new ConsistencyException("No Handler For " + context.toString());
	}

	@Override
	public void retry(ConsistencyContext context) {
		for (ConsistencyHandler handler : handlers) {
			if (handler.support(context)) {
				handler.retry(context);
				return;
			}
		}
		throw new ConsistencyException("No Handler For " + context.toString());
	}
}